package com.pt25.base.dep.shardingjdbc.datasource;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 数据源选择处理切面
 */
@Aspect
@Component
public class DatasourceAspect {

    @Around(value = "@annotation(com.pt25.base.dep.shardingjdbc.datasource.Datasource)")
    public Object datasource(ProceedingJoinPoint joinPoint) throws Throwable {
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        Datasource datasource = method.getAnnotation(Datasource.class);
        if (datasource != null) {
            MultiDatasourceContext.setDataSource(datasource.value());
        }
        Object result = joinPoint.proceed();
        MultiDatasourceContext.clear();
        return result;
    }
}
